//
//  LLCalendarViewController.swift
//  LiLi
//
//  Created by liuzhu on 2019/1/5.
//  Copyright © 2019 liuzhu. All rights reserved.
//

import UIKit
private let LLDayReuseIdentifier = "LLDayReuseIdentifier" // 全局
class LLCalendarViewController: LLBaseViewController {
    var titleBtn: TitleButton = TitleButton()
    var selectedDateStr: String = LLDateUtil.shareLLDateUtil().dateConverString(date: LLDateUtil.shareLLDateUtil().getCurrentDate(), dateFormat: "yyyy-MM-dd")
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNav()
        // 注册一个cell
        collectionView.register(LLCalendarCell.self, forCellWithReuseIdentifier: LLDayReuseIdentifier)
        view.addSubview(weekView)
        view.addSubview(collectionView)
        view.addSubview(snapShotView)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "今日", style: UIBarButtonItem.Style.plain, target: self, action: #selector(today))
        navigationItem.rightBarButtonItem?.tintColor = UIColor.red

        reloadDays(dateStr: "\(LLDateUtil.shareLLDateUtil().getCurrentYearAndMonth())")
        NotificationCenter.default.addObserver(self, selector: #selector(listenActionWillAdd), name: NSNotification.Name(rawValue: LLActionWillAddKey), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(listenDaysAndActionUpdated(_:)), name: NSNotification.Name(rawValue: LLDaysAndActionUpdatedKey), object: nil)
        snapShotView.backDay = { day in
            let vc = LLTodayActionViewController()
            vc.day = day
            self.navigationController?.pushViewController(vc, animated: false)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
         self.tabBarController?.tabBar.isHidden = false
    }
    
    private func setupNav() {
        // 标题按钮
        titleBtn.setTitle("\(LLDateUtil.shareLLDateUtil().getCurrentYearAndMonth()) ", for: UIControl.State.normal)
        titleBtn.addTarget(self, action: #selector(titleClick), for: UIControl.Event.touchUpInside)
        navigationItem.titleView = titleBtn
    }

    // MARK: - 懒加载
    private lazy var days: [LLDay] = [LLDay]()
    private var weekView: LLWeekView = {
        var y = CGFloat(65)
        if LLConst.getPhoneType() == PhoneType.PHONE_MAX_XR || LLConst.getPhoneType() == PhoneType.PHONE_X {
            y = 90
        }
        let ve = LLWeekView(frame: CGRect(x: 5, y: y, width: UIScreen.main.bounds.size.width - 10, height: 40))
        ve.backgroundColor = LLConst.backgroundGray()
        ve.currentWeek = LLDateUtil.shareLLDateUtil().currentWeek()
        return ve
    }()

    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let width = (UIScreen.main.bounds.size.width - 10) / 7
        layout.itemSize = CGSize(width: width, height: width)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = UICollectionView.ScrollDirection.vertical
        let coll = UICollectionView(frame: CGRect(x: 0, y: weekView.frame.origin.y + weekView.bounds.size.height + 10, width: UIScreen.main.bounds.size.width - 10, height: UIScreen.main.bounds.size.height - weekView.bounds.size.height - 90), collectionViewLayout: layout)
        coll.delegate = self
        coll.dataSource = self
        coll.showsVerticalScrollIndicator = false
        coll.bounces = false
        coll.backgroundColor = UIColor.white
        return coll
    }()

    private lazy var snapShotView: LLActionSnapshotView = {
        var height = CGFloat(50)
        if LLConst.getPhoneType() == PhoneType.PHONE_MAX_XR || LLConst.getPhoneType() == PhoneType.PHONE_X {
            height = 80
        }
        let ve = LLActionSnapshotView(frame: CGRect(x: 0, y: UIScreen.main.bounds.size.height - (height + 120), width: UIScreen.main.bounds.size.width, height: 120))
        return ve
    }()

    @objc private func titleClick(btn: TitleButton) {
        let dataPicker = EWDatePickerViewController()
        dataPicker.datePickeTypes = [DatePickerType.DATEPICKERTYPE_YEAR, DatePickerType.DATEPICKERTYPE_MONTH]
        dataPicker.dateStyle = DatePickerStyle.DATEPICKERSTYLE_DATESELECT
        definesPresentationContext = true
        /// 回调显示方法
        dataPicker.backDate = { [weak self] date in
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "YYYY-MM"
            self!.titleBtn.setTitle(date, for: UIControl.State.normal)
            self?.reloadDays(dateStr: date)
        }
        dataPicker.view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3)
        dataPicker.picker.reloadAllComponents()

        /// 弹出时日期滚动到当前日期效果
        present(dataPicker, animated: true) {
            dataPicker.picker.selectRow(LLDateUtil.shareLLDateUtil().currentYear() - minYear, inComponent: 0, animated: true)
            dataPicker.picker.selectRow(LLDateUtil.shareLLDateUtil().currentMonth() - 1, inComponent: 1, animated: true)
        }
    }

    @objc private func listenActionWillAdd() {
        // 判断是否开启了本地通知
        if UIApplication.shared.currentUserNotificationSettings?.types == UIUserNotificationType(rawValue: 0) {
            let alert = UIAlertController(title: "开启通知", message: "开启通知后，才可以创建日程", preferredStyle: UIAlertController.Style.alert)
            let action = UIAlertAction(title: "去开启", style: .default, handler: { _ in
                let settingUrl = NSURL(string: UIApplication.openSettingsURLString)!
                if UIApplication.shared.canOpenURL(settingUrl as URL) {
                    UIApplication.shared.openURL(settingUrl as URL)
                }
            })

            let actionCancel = UIAlertAction(title: "不开启", style: .default, handler: { _ in
            })
            alert.addAction(action)
            alert.addAction(actionCancel)
            present(alert, animated: true, completion: nil)
            return
        }

        let dataPicker = EWDatePickerViewController()
        dataPicker.datePickeTypes = [DatePickerType.DATEPICKERTYPE_YEAR, DatePickerType.DATEPICKERTYPE_MONTH, DatePickerType.DATEPICKERTYPE_DAY, DatePickerType.DATEPICKERTYPE_HOUR, DatePickerType.DATEPICKERTYPE_MIN]
        dataPicker.dateStyle = DatePickerStyle.DATEPICKERSTYLE_ACTIONADD
        dataPicker.backActionInfo = { name, des, type, repeatTag, dic in

            DispatchQueue.main.async {
                dataPicker.dismiss(animated: true, completion: nil)
                SVProgressHUD.show(withStatus: "请稍后")
            }
            let query = DispatchQueue(label: "createAction")
            query.async {
                LLManager.shareLLManager().createAction(actionType: type, repeatTag: repeatTag, titleName: name, des: des, dateDic: dic, finish: { _, result, message in
                    if result {
                        SVProgressHUD.showSuccess(withStatus: message)
                    } else {
                        SVProgressHUD.showError(withStatus: message)
                    }
                })
            }
        }
        dataPicker.view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3)
        dataPicker.picker.reloadAllComponents()
        /// 弹出时日期滚动到当前日期效果
        present(dataPicker, animated: true) {
            dataPicker.picker.selectRow(LLDateUtil.shareLLDateUtil().currentYear() - minYear, inComponent: 0, animated: true)
            dataPicker.picker.selectRow(LLDateUtil.shareLLDateUtil().currentMonth() - 1, inComponent: 1, animated: true)
            dataPicker.picker.selectRow(LLDateUtil.shareLLDateUtil().currentDay() - 1, inComponent: 2, animated: true)
        }
    }

    @objc private func listenDaysAndActionUpdated(_ notification: Notification) {
        reloadDays(dateStr: "\(LLDateUtil.shareLLDateUtil().getCurrentYearAndMonth())")
    }

    @objc private func today() {
        let date = LLDateUtil.shareLLDateUtil().getCurrentDate()
        let dateStr = LLDateUtil.shareLLDateUtil().dateConverString(date: date, dateFormat: "yyyy-MM")
        selectedDateStr = LLDateUtil.shareLLDateUtil().dateConverString(date: date, dateFormat: "yyyy-MM-dd")
        titleBtn.setTitle(dateStr, for: UIControl.State.normal)
        reloadDays(dateStr: dateStr)
    }

    private func reloadDays(dateStr: String) {
        if dateStr.contains("-") {
            LLManager.shareLLManager().loadDays(yearAndMonth: dateStr, finish: { days, _ in
                if days != nil {
                    self.days = days!
                    DispatchQueue.main.async {
                        self.collectionView.reloadData()
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                }
                }
            })
        }
        LLDayManager.shareDayManager().loadDay(dateStr: selectedDateStr) { day, isSuccess in
            if isSuccess {
                self.snapShotView.day = day
            }
        }
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension LLCalendarViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return days.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // 获取cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: LLDayReuseIdentifier, for: indexPath) as! LLCalendarCell
        // 设置cell的数据
        let day = days[indexPath.row]
        cell.day = day
        // 返回cell
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let day = days[indexPath.row]
        if day.dayStatus != DayStatusEnum.DAYSTATUS_NODATE {
            snapShotView.day = day
        }
    }
}
